package com.hrg.demo.controller;

import com.hrg.demo.config.ImagesConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shenzq
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/apiImages")
@CrossOrigin
public class ImageController {

    //private final String IMAGE_BASE_DIR = "D:/images/";

    private final ImagesConfig imagesConfig;


    /**
     * 将绝对路径转换为Web可访问的URL
     */
    @PostMapping("/convertPath")
    public Map<String, Object> convertImagePath(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();

        String absolutePath = request.get("path");
        log.info("absolutePath 图片路径:"+absolutePath);
        if (absolutePath == null || absolutePath.trim().isEmpty()) {
            response.put("success", false);
            response.put("message", "图片路径不能为空");
            throw new RuntimeException("图片路径不能为空");
        }

        try {
            // 标准化路径
            Path filePath = Paths.get(absolutePath).toAbsolutePath().normalize();
            Path basePath = Paths.get(imagesConfig.getImageBaseDir()).toAbsolutePath().normalize();

            // 安全检查：确保文件在指定目录内
            if (!filePath.startsWith(basePath)) {
                response.put("success", false);
                response.put("message", "当前图片的路径为"+absolutePath+",图片必须在 " + imagesConfig.getImageBaseDir() + " 目录下");
                throw new RuntimeException("当前图片的路径为"+absolutePath+",图片必须在 " + imagesConfig.getImageBaseDir() + " 目录下");
            }

            // 检查文件是否存在
            if (!Files.exists(filePath)) {
                response.put("success", false);
                response.put("message", "当前图片的路径为"+absolutePath+",文件不存在: " + filePath);
                throw new RuntimeException("当前图片的路径为"+absolutePath+",文件不存在: " + filePath);
            }

            // 检查是否是图片文件
            String fileName = filePath.getFileName().toString().toLowerCase();
            if (!fileName.matches(".*\\.(jpg|jpeg|png|gif|bmp|webp)$")) {
                response.put("success", false);
                response.put("message", "当前图片的路径为"+absolutePath+",不支持的文件格式，请选择图片文件");
                throw new RuntimeException("当前图片的路径为"+absolutePath+",不支持的文件格式，请选择图片文件");
            }

            // 转换为Web URL
            String relativePath = basePath.relativize(filePath).toString();
            String webUrl = "/"+imagesConfig.getLocalImages()+"/" + relativePath.replace("\\", "/");

            response.put("success", true);
            response.put("webUrl", webUrl);
            response.put("fileName", fileName);

        } catch (Exception e) {
            log.error(e.getMessage());
            response.put("success", false);
            response.put("message", "路径转换方法失败: " + e.getMessage());
        }
        log.info("response: " + response.toString() );
        return response;
    }
}
